<?php
require_once 'Translator/Model.php';

/**
 * Language model.
 */
class LanguageModel extends Translator_Model {
	/**
	 * Fetch all languages a certain user has access to.
	 * 
	 * @remark This method is not intended to be used for administrators,
	 * 			as they have access to all materials without explicit connections
	 * 			modelled in the database. 
	 */
	public function fetchLanguagesByUser($userid, $original = false) {
		return $this->_db->fetchAll(
			'SELECT l.* 
			 FROM user_languages AS ul
			 LEFT JOIN languages AS l ON ul.language = l.id
			 WHERE ul.user = ? '.
			(!$original ? ' AND l.original = 0 ' : '').
			'ORDER BY name ASC',
			array($userid)
		);
	}
	
	/**
	 * Fetch all languages.
	 */
	public function fetchLanguages($original = false) {
		return $this->_db->fetchAll(
			'SELECT * FROM languages '.
			(!$original ? 'WHERE original = 0 ' : '').
			'ORDER BY original DESC, name ASC');
	}
	
	/**
	 * Fetch language by code.
	 * 
	 * @param string $code
	 */
	public function fetchLanguage($code) {
		return $this->_db->fetchRow(
			'SELECT * FROM languages WHERE code = ? LIMIT 1',
			array($code)
		);
	}
	
	/**
	 * Save what languages a user can translate.
	 * 
	 * @param int $userid
	 * @param array $languages Array with language IDs
	 */
	public function saveUserLanguages($userid, $languages) {
		/*
		 * brute force:
		 * 1. remove all user languages
		 * 2. create new records for passed languages
		 */
		
		$this->_db->delete('user_languages', 'user = '.intval($userid));
		
		// construct
		$sql = 'INSERT INTO user_languages (user, language) VALUES ';
		
		$first = true;
		foreach ($languages as $language) {
			if(!$first) {
				$sql .= ',';
			} else {
				$first = false;
			}
			
			$sql .= '('.intval($userid).', '.intval($language).') ';
		}
		
		$this->_db->query($sql);
	}
}